<template>
  <div class="background">
    <el-card class="login">
      <template #header>
        <div class="card-header">
          <h3>网上书店后台系统</h3>
        </div>
      </template>
      <el-form :model="loginModel" class="login-form">
        <el-form-item label="用户名">
          <el-input v-model="loginModel.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="loginModel.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <div class="code">
            <el-input class="m_input" v-model="loginModel.code"></el-input>
            <span @click="getCode" v-html="codeImg"></span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="login" type="primary">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import {
  ElMessage,
  ElCard,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
} from "element-plus";
import { defineComponent, ref, watchEffect } from "vue";

import { http } from "../http";
import { Login } from "../interface/login.interface";
import { useRouter } from "vue-router";

export default defineComponent({
  name: "Login",
  components: {
    ElMessage,
    ElCard,
    ElButton,
    ElForm,
    ElFormItem,
    ElInput,
  },
  setup() {
    const router = useRouter();
    const loginModel = ref({} as Login);
    const codeImg = ref(null as any);

    async function getCode() {
      codeImg.value = (await http.get("/verifcode")).data.image;
    }

    getCode();

    async function login() {
      try {
        const data = (await http.post("/login", loginModel.value)).data;
        localStorage.token = data.token;
        router.push("/");
        ElMessage.success("登录成功");
      } catch (e) {
        ElMessage.error("登录失败");
        getCode();
      }
    }
    return { loginModel, login, codeImg, getCode };
  },
});
</script>
>

<style lang="scss">
.background {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../assets/images/wallroom-1920x1080-bg-8841766.jpg") center
    no-repeat;

  .login {
    width: 50%;

    h3 {
      margin: 0;
    }

    .login-form {
      padding: 0 30px;

      .code {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .m_input {
          width: 65%;
        }

        span {
          cursor: pointer;
          width: 30%;
        }
      }
    }
  }
}
</style>
